<?php
/**
 *	  [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *	  This is NOT a freeware, use is subject to license terms
 *
 *	  http://www.haidao.la
 *	  tel:400-600-2042
 */
class AdminWithdrawLogController extends AdminBaseController {
	/**
	 * 自动执行
	 */
	public function _initialize() {
		parent::_initialize(); 
		$this->db = model("user_withdraw");
	}

	/**
	 * 会员财务管理
	 */   
	public function index() {
		
		if($_GET["act"]=="excel"){
			
			$keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
			//分页
			$sqlmap = array();
			if (isset($keyword) && $keyword) {
				$sqlmap['_string'] = "u.username LIKE '%{$keyword}%'";
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['a.add_time'] =array('between',$start.','.$end);
			}
			if ($_GET["status"]!="") {
				$sqlmap['a.withdraw_status'] = $_GET["status"]-1;
			}
			$join = "LEFT JOIN `__USER__` AS u ON a.uid = u.id";
			$result = $this->db->alias('a')->join($join)->where($sqlmap)->order("a.id desc");
			
			$headerArr = array('username'=>'会员名 ',
				'user_type'=>'会员类型 ',
				'withdraw_money'=>'提现金额 ',
				'withdraw_fee'=>'手续费 ',
				'now_money'=>'到账金额 ',
				'true_name'=>'真实姓名',
				'banknum'=>'银行卡号 ',
				'bankaddress'=>'开户地址',
				'add_time'=>'时间',
				'withdraw_status'=>'状态',
				'deal_info'=>'处理意见 ',
			);
			$this->DownloadCSV( $result, $headerArr);
			exit;
		}
		
		if (IS_POST) {
			$keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
			//分页
			$sqlmap = array();
			if (isset($keyword) && $keyword) {
				$sqlmap['_string'] = "u.username LIKE '%{$keyword}%'";
			}
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['a.add_time'] =array('between',$start.','.$end);
			}
			if ($_GET["status"]!="") {
				$sqlmap['a.withdraw_status'] = $_GET["status"]-1;
			}
			$join = "LEFT JOIN `__USER__` AS u ON a.uid = u.id";
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$result = $this->db->lists($_GET);
			if (!$result) $result=array();
			$data = array();
			$data['total'] = $this->db->alias('a')->join($join)->where($sqlmap)->count();	//计算总数  
			$data['money'] = $this->db->alias('a')->join($join)->where($sqlmap)->sum("a.withdraw_money");	//计算总数  
			$data['rows'] = $result;
			$data['title']="统计概览--提现数量：".($data["total"]==""?0:$data["total"])."    提现金额：".($data["money"]==""?"0.00":$data["money"])."元";
			$data['status_type'] = array(array("id"=>1,"name"=>"未处理"),array("id"=>2,"name"=>"已提现"),array("id"=>3,"name"=>"提现失败"));
			echo json_encode($data);
		}else {
			$pays = getcache('payment', 'pay');
			if ($pays['ws_wap']['pay_name']) $pays['ws_wap']['pay_name'] = $pays['ws_wap']['pay_name'].' (不支持)';
			if ($pays['alipay_escow']['pay_name']) $pays['alipay_escow']['pay_name'] = $pays['alipay_escow']['pay_name'].' (不支持)';
			include $this->admin_tpl('admin_withdraw_log');
		}
	}
	private function DownloadCSV($selectObject,$head){
		$fileName=time();
		if ( !is_object( $selectObject ) || !is_array( $head ) ) {
			exit('参数错误!');
		}
		set_time_limit(0);
		//下载头.
		header ('Content-Type: application/vnd.ms-excel;charset=gbk');
		header ('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
		header ('Cache-Control: max-age=0');
		//输出流;
		$file = 'php://output';
		$fp = fopen ( $file, 'a' );

		function changCode( $changArr ) {
			// 破Excel2003中文只支持GBK编码;
			foreach ( $changArr as $k => $v ) {
				$changArr [$k] = iconv ( 'utf-8', 'gbk', $v );
			}
			//返回一个 索引数组;
			return array_values( $changArr );
		};
		//写入头部;
		fputcsv ( $fp, changCode( $head ) );

		//写入数据;
		$pageSize = 100;//每次查询一百条;
		$page  = 1;//起始页码;
		$list = array();
		//查库;
		$cloneObj = clone $selectObject;//因为thinkphp内部执行完select方法后会清空对象属性,所以clone;
		$t_status=array( "0" => "未处理", "1" => "已提现", "2" => "提现失败");
		while ( $list = $cloneObj ->limit( $pageSize*( ($page++)-1 ), $pageSize )->select()  ) {
			$cloneObj = clone $selectObject;
			//对查询结果二次处理
			foreach ( $list as $key => $value ) {
				$value['username']=str_replace(" "," ",trim($value["username"]));
				$value['add_time']= date('Y-m-d H:i',$value['add_time']); 
				$value['withdraw_status']=$t_status[$value["withdraw_status"]];
				$value['banknum']="'".$value["banknum"];
				if($value["user_type"]==1){
					$value['user_type']="个人"; 
				}else{
					$value['user_type']="商家"; 
				}
				$value['now_money']=bcsub($value["withdraw_money"],$value["withdraw_fee"],2);
				$value = array_intersect_key( $value, $head );//返回需要写入CSV的数据;
				$value = array_merge( $head, $value );//利用此函数返回需要的顺序;
				$value = changCode( $value );
				fputcsv ( $fp, $value );//写入数据;
				flush();
			}
			ob_flush();
		}
		exit();
	}
	
	
	public function doedit(){
		$infos=M("user_withdraw")->find(I("id"));
		
		if($infos["withdraw_status"]>0){
			$json['status'] = 1;
			$json['id'] = I("id");
			$json['info'] = '当前提现已经处理。';
			die(json_encode($json));
		}
		if(I("withdraw_status")==1){
			model('user')->where(array('id' => $infos["uid"]))->setDec('freeze_money',$infos["withdraw_money"]);	
			$money_info=model('user')->find($infos["uid"]);
			$data             = array();
			$data['user_id']  = $infos["uid"];
			$data['money']    =-(I("withdraw_fee"));
			$data['msg']      = '提现成功提现扣除手续费'.I("withdraw_fee").'元,实际到账'.bcsub($infos["withdraw_money"],I("withdraw_fee"),2);
			$data['dateline'] = NOW_TIME;
			$data['type'] = 6;
			$data['user_money'] = $money_info["user_money"];
			$data['freeze_money'] = $money_info["freeze_money"];
			M('user_moneylog')->add($data);
			$save["withdraw_status"]=1;
			$save["deal_time"]=time();
			$save["deal_user"]=ADMIN_ID;
			$save["deal_info"]=I("deal_info");
			$save["withdraw_fee"]=I("withdraw_fee");
			M("user_withdraw")->where("id=".I("id"))->save($save);
			$json['status'] = 1;
			$json['id'] = I("id");
			$json['info'] = '提现处理成功。';
			$json['deal_info'] = I("deal_info");
			die(json_encode($json));	
		}else{
			model('user')->where(array('id' => $infos["uid"]))->setInc('user_money',$infos["withdraw_money"]);
			model('user')->where(array('id' => $infos["uid"]))->setDec('freeze_money',$infos["withdraw_money"]);
			$money_info=model('user')->find($infos["uid"]);	
			$data             = array();
			$data['user_id']  = $infos["uid"];
			$data['money']    =$infos["withdraw_money"];
			$data['msg']      = '提现失败，返回冻结金额';
			$data['dateline'] = NOW_TIME;
			$data['type'] = 5;
			$data['user_money'] = $money_info["user_money"];
			$data['freeze_money'] = $money_info["freeze_money"];
			M('user_moneylog')->add($data);
			$save["withdraw_status"]=2;
			$save["deal_time"]=time();
			$save["deal_user"]=ADMIN_ID;
			$save["deal_info"]=I("deal_info");
			M("user_withdraw")->where("id=".I("id"))->save($save);
			$json['status'] = 2;
			$json['id'] = I("id");
			$json['info'] = '提现处理成功。';
			$json['deal_info'] = I("deal_info");
			die(json_encode($json));	
		}
		
		
	}
	

}